package com.micai.springboot.controller.admin;

import com.micai.springboot.base.BaseController;
import com.micai.springboot.dto.UserDto;
import com.micai.springboot.service.MenuService;
import com.micai.springboot.vo.tree.TreeMenuVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 描述：
 * <p>
 * Author: 赵新国
 * Date: 2017/11/13 12:07
 */
@Controller
@RequestMapping("/admin")
public class AdminIndexController extends BaseController {

    @Autowired
    private MenuService menuService;

    /**
     * 后台首页
     * @return
     */
    @RequestMapping("/index")
    public String adminIndex(Model model) {
        return "admin/index";
    }

    /**
     * 后台首页
     * @return
     */
    @RequestMapping("/main")
    public String adminMain(Model model, HttpServletRequest request) {
        // 获取当前登录用户ID
        /*UserDto userDto = (UserDto) sessionProvider.getAttribute(request, Constants.ADMIN_SESSION);*/
        Subject subject = SecurityUtils.getSubject();
        UserDto userDto = (UserDto) subject.getPrincipal();
        if (userDto == null) {
            return "redirect:/admin/toLogin";
        }
        // 根据用户ID，查询对应的左侧菜单树、先从缓存中加载，缓存没有，再查询DB
        List<TreeMenuVo> menuTree = null;
        // 一级缓存
        Cache.ValueWrapper leftMenuTreeCache = getLeftMenuTreeCacheName().get(userDto.getId());
        if (leftMenuTreeCache != null && leftMenuTreeCache.get() != null) {
            menuTree = (List<TreeMenuVo>)leftMenuTreeCache.get();
            model.addAttribute("menuTree", menuTree);
        } else {
            // 二级缓存
            Object sendMenuTreeCache = redisTemplate.opsForHash().get(userDto.getId(), userDto.getId());
            if (sendMenuTreeCache != null) {
                menuTree = (List<TreeMenuVo>)sendMenuTreeCache;
                model.addAttribute("menuTree", menuTree);
            } else {
                menuTree = menuService.getLeftMenuByTree(null, 0L, userDto.getId());
                // 加入一级缓存
                getLeftMenuTreeCacheName().put(userDto.getId(), menuTree);
                // 加入二级缓存
                redisTemplate.opsForHash().put(userDto.getId(), userDto.getId(), menuTree);
                model.addAttribute("menuTree", menuTree);
            }
        }
        return "admin/index";
    }
}
